/**
 * Writed by yura and mak
 */

package wz.legend.util;

import org.apache.log4j.Logger;
import org.w3c.dom.Node;

import java.awt.*;
import java.util.List;

/**
 * User: yura
 */
public class ItemUtils {

    private static final Logger LOG = Logger.getLogger(ItemUtils.class);

    public static double calculateMinimalDistance(Node node, List<Node> nodeList) {
        String nodeName = Utils.getAttributeValue(node, "name");
        Point farmPos = Utils.getItemPosition(node);
        double minDistance = Double.MAX_VALUE;
        for (Node bot : nodeList) {
            Point botPos = Utils.getItemPosition(bot);
            String botName = Utils.getAttributeValue(node, "name");

            double distance = Math.sqrt(Math.pow(farmPos.x - botPos.x, 2)
                    + Math.pow(farmPos.y - botPos.y, 2));
            if (distance != 0 || !botName.equals(nodeName)) {
                if (distance < minDistance) {
                    minDistance = distance;
                }
            }
        }
        return minDistance;
    }

    public static Node findBestItem(List<Node> farmsList, List<Node> botsList,
            int minStartDistance, boolean findMaxDistance) throws Exception {
        if (findMaxDistance) {
            double maxDistance = 0;
            Node node = null;
            for (Node item : farmsList) {
                double distance = ItemUtils.calculateMinimalDistance(item,
                        botsList);
                if (maxDistance < distance) {
                    maxDistance = distance;
                    node = item;
                }
            }
            if (node != null) {
                if (maxDistance >= minStartDistance) {
                    LOG.debug("Node found: \t"
                            + Utils.getAttributeValue(node, "name")
                            + "\tdistance=" + maxDistance);
                } else {
                    node = null;
                }
            }
            return node;
        } else {
            return farmsList.get(0);
        }
    }
}
